import axios from 'axios';
import type {
  AxiosError,
  AxiosInstance,
  AxiosRequestConfig,
  AxiosResponse,
} from 'axios';
import { AxiosCanceler } from './helper/axiosCancel';
import { checkStatus } from './helper/checkStatus';
import { RequestHttpEnum, axiosConfig, StatusEnum } from './helper/config';
import { message } from 'antd';

interface ResultData<T = any> {
  code: number;
  message: string;
  data: T extends any ? T : T & any;
}

const axiosCanceler = new AxiosCanceler();

class Http {
  public service: AxiosInstance;

  public constructor(config: AxiosRequestConfig) {
    this.service = axios.create(config);

    this.init();
  }

  init() {
    /**
     * @description 请求拦截器
     * token校验(JWT) : 接受服务器返回的token,存储到pinia/本地储存当中
     */
    this.service.interceptors.request.use(
      config => {
        // * 将当前请求添加到 pending 中
        axiosCanceler.addPending(config);

        // const token = localStorage.getItem('token') || ''
        // if (token && config.headers) {
        //   typeof config.headers.set === 'function' && config.headers.set('Authorization', token)
        // }

        return { ...config };
      },
      (error: AxiosError) => {
        // 请求报错
        return Promise.reject(error);
      },
    );

    /**
     * @description 响应拦截器
     */
    this.service.interceptors.response.use(
      (response: AxiosResponse) => {
        const { data, config } = response;
        // * 在请求结束后，移除本次请求
        axiosCanceler.removePending(config);
        // * 全局错误信息拦截（防止下载文件得时候返回数据流，没有code，直接报错）
        if (data.code && data.code !== StatusEnum.SUCCESS) {
          checkStatus(response);
          return Promise.reject(data);
        }
        // * 成功请求
        return data;
      },
      async (error: AxiosError) => {
        const { response } = error;
        // 根据响应的错误状态码，做不同的处理
        if (response) return checkStatus(response);
        // // 服务器结果都没有返回(可能服务器错误可能客户端断网)，断网处理:可以跳转到断网页面
        if (!window.navigator.onLine) {
          message.error('网络连接失败');
        }
        return Promise.reject(error);
      },
    );
  }
  // * 常用请求方法封装
  [RequestHttpEnum.GET]<T>(
    url: string,
    params?: object,
    _object = {},
  ): Promise<ResultData<T>> {
    return this.service[RequestHttpEnum.GET](url, {
      params,
      ..._object,
    });
  }
  [RequestHttpEnum.POST]<T>(
    url: string,
    params?: object,
    _object = {},
  ): Promise<ResultData<T>> {
    return this.service[RequestHttpEnum.POST](url, params, _object);
  }
  [RequestHttpEnum.PUT]<T>(
    url: string,
    params?: object,
    _object = {},
  ): Promise<ResultData<T>> {
    return this.service[RequestHttpEnum.PUT](url, params, _object);
  }
  [RequestHttpEnum.DELETE]<T>(
    url: string,
    params?: any,
    _object = {},
  ): Promise<ResultData<T>> {
    return this.service[RequestHttpEnum.DELETE](url, { params, ..._object });
  }
}
export default new Http(axiosConfig);
